package com.jlkf.controller;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.jlkf.pojo.OrderItems;
import com.jlkf.service.util.FireBaseUtil;
import com.jlkf.service.util.StringTools;
import com.jlkf.service.OrderItemsService;
import com.jlkf.service.UserService;
import com.platform.server.response.response.pojo.ReturnData;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("orderItems")
public class OrderItemsController {

	@Autowired
	private OrderItemsService orderItemsService;
	@Autowired
	private UserService userService;
	
	/**
	 * 用户端  是否有未完成支付订单 
	 * @param uId
	 * @return
	 */
	@RequestMapping("getMyuncompletedOrder")
	public Object getMyuncompletedOrder(Long uId){
		return orderItemsService.getMyuncompletedOrder(uId);
	}
	/**
	 * 司机端  是否有未完成支付的订单
	 * @param driverId
	 * @return
	 */
	@RequestMapping("driverGetMyuncompletedOrder")
	public Object driverGetMyuncompletedOrder(Long driverId){
		return orderItemsService.driverGetMyuncompletedOrder(driverId);
	}
	//支付余额不足的订单接口  需要提供订单id 支付的ip 用户使用的银行卡  
	@RequestMapping("payLessThan")
	public Object payLessThan(@RequestBody String json){
		return orderItemsService.payLessThan(json);
	}
	//是否有服务于concierge的司机
	@RequestMapping("isNotConcierge")
	public Object isNotConcierge(Double lng,Double lat, String cityName){
		return orderItemsService.isNotConcierge(lng, lat,cityName);
	}
	/*@RequestMapping("createFile")
	public Object createFile(String result,HttpServletRequest request,String orderId){
		if (!StringUtils.isEmpty(result)) {
			JSONArray jarr=JSONArray.fromObject(result);
			 String realPath =  request.getSession().getServletContext().getRealPath("/");
             String path2 = realPath.substring(0,realPath.lastIndexOf(System.getProperty("file.separator")));
             String p = realPath.substring(0, (path2.lastIndexOf(System.getProperty("file.separator"))))+System.getProperty("file.separator")+"file"+System.getProperty("file.separator")+"FABposition";
			 File file = new File(p); 
			//把字符串转换成list
			if (!file.exists()) {
				file.mkdir();
	            System.err.println(file + "已创建！");
	        }
			 File file1 = new File(p, orderId+".txt"); 
			 if (!file1.exists()) {
					try {
						file1.createNewFile();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		            System.err.println(file + "已创建！");
		        }
			 byte bt[] = new byte[1024];  
		        bt = result.getBytes();  
		        try {  
		            FileOutputStream in = new FileOutputStream(file1);  
		            try {  
		            	   in.write(bt, 0, bt.length);  
			                in.close(); 
		            } catch (IOException e) {  
		                // TODO Auto-generated catch block  
		                e.printStackTrace();  
		            }  
		        } catch (FileNotFoundException e) {  
		            // TODO Auto-generated catch block  
		            e.printStackTrace();  
		        }  
		}
		return orderId;
	}*/
	
	//测试获取google里程  传的是经纬度
	@RequestMapping("google")
	@ResponseBody
	public Object google(@RequestBody String json){
		JSONObject jo = JSONObject.fromObject(json);
		String origins=(String) jo.get("origins");
		String destinations=(String) jo.get("destinations");
		return orderItemsService.getGoogleMileage(origins,destinations);
	}
	//获取fireBase
	@RequestMapping("getfireBaseAccessToken")
	@ResponseBody
	public static String getAccessToken(HttpServletRequest request) throws IOException {
		  String realPath =  request.getSession().getServletContext().getRealPath("/");
          String path2 = realPath.substring(0,realPath.lastIndexOf(System.getProperty("file.separator")))+System.getProperty("file.separator")+"firebaseDataBase"+System.getProperty("file.separator")+"fabdriverapp-firebase-adminsdk-ou2ng-f7fe56a315.json";
		System.out.println("firebase____json_____url==="+path2);
		
		  GoogleCredential googleCredential = GoogleCredential
		      .fromStream(new FileInputStream(path2))
		      .createScoped(Arrays.asList("5"));
		  googleCredential.refreshToken();
		  return googleCredential.getAccessToken();
		}
	
	@RequestMapping("sendSMS")
	@ResponseBody
	public Object sendSMS(HttpServletRequest request,String telephone,Integer platform,String context) throws IOException{
		  return userService.sendSMS(telephone, platform, context);
		
	}
	
	
	//测试使用fireBase发送通知
	@RequestMapping("sendMessageAlertDriver")
	@ResponseBody
	public  Object sendMessageAlertDriver(@RequestBody String json) throws IOException {
		String result="";
		 try {
			Map<String,Object> m = StringTools.jsonToMap(json);
		        HttpURLConnection httpcon = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send").openConnection()));
		        httpcon.setDoOutput(true);
		        httpcon.setRequestProperty("Content-Type", "application/json");
		        httpcon.setRequestProperty("Authorization", "key=AAAA0u4bEGw:APA91bFF2dBX9Wo2xTE5f0mbrYheZZNkJ1nxlIyCHgEOPPFA_ROT4eHwSDnhk8qc6hSXObTWyC-91ueWatrOz4rwPjosKJdPy3f1QbrPzTFbR6yHB_0mpye62txZWdKpli-DSgPhEDek");
		        httpcon.setRequestMethod("POST");
		        httpcon.connect();
		        System.out.println("Connected!");
               String mm=(String) m.get("to");
               String d="{\"notification\":{\"title\": \"My title\", \"text\": \"My text\", \"sound\": \"default\"}, \"to\": \""+mm+"\"}";
		        byte[] outputBytes = d.getBytes("UTF-8");
		        OutputStream os = httpcon.getOutputStream();
		        os.write(outputBytes);
		        os.close();
		        // Reading response
		        InputStream input = httpcon.getInputStream();
		        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
		            for (String line; (line = reader.readLine()) != null;) {
		                System.out.println(line);
		                result+=line;
		            }
		        }
		        System.out.println("Http POST request sent!");
		        return new ReturnData(result,200,"success");
		    } catch (IOException e) {
		        e.printStackTrace();
		        return new ReturnData(500,"fail");
		    }
		 
		}
	@RequestMapping("/fireBaseDataBase")
	public Object fireBaseDataBase() {
		try {
			String token=FireBaseUtil.getAccess();
			return new ReturnData(token,200,"success");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnData(500,"fail");
		}
	}
	
	/**
	 * 首页获取预估价
	 * @param mileage 里程
	 * @param time 时长
	 * @param uId 用户id
	 * @param trafficJamTime 堵车时长
	 * @param   toll_station   收费站
	 * @return
	 */
	//String mileage, String time,Long uId,String trafficJamTime,String toll_station
	@RequestMapping("getHomePageEstimate")
	public Object getHomePageEstimate(@RequestBody String json){
		OrderItems oi = StringTools.json2Obj(json, OrderItems.class);
		return orderItemsService.getHomePageEstimate(oi.getMileage().toString(), oi.getTimes().toString(), oi.getuId(), oi.getTrafficJamTime(),oi.getPointCharges(),oi.getDeparturePosition(),oi.getArrivedPosition());
	}
	
	
	//确认下单
	@RequestMapping("confirmTheOrder")
	public Object confirmTheOrder(@RequestBody String json){
		return orderItemsService.confirmTheOrder(json);
	}
	
	/**
	 * 打赏小费支付
	 * @param orderId 订单
	 * @param exceptionalATip 打赏的金额
	 * @param ubId 支付的银行卡
	 * @return
	 */
	@RequestMapping("exceptionalTip")
	public Object exceptionalTip(@RequestBody String json){
		return orderItemsService.exceptionalTip(json);
	}
	
	/**
	 * 计价规则详情
	 * @param type
	 * @return
	 */
	@RequestMapping("valuationRules")
	public Object valuationRules(){
		return orderItemsService.valuationRules();
	}
	/**
	 * 获取我的银行卡
	 * @param uId
	 * @return
	 */
	@RequestMapping("getMyBrank")
	public Object getMyBrank(Long uId){
		return orderItemsService.getMyBrank(uId);
	}
	
	/**
	 *  * 用户端  司机列表  附近的车-附近半径5公里范围内的在线的并允许此服务的车辆【3分钟内可以接单、空闲】
	 * @param lng 经度
	 * @param lat 纬度
	 * @param cityName 城市名称
	 * @param distance  1 距离远   2 近
	 * @param appraise   评价 1高 分数高  2 低 分数低
	 * @param singularNum   单数 1 高 2低 
	 * @param  carType  服务类型 1fab ONE 2fab 3fab PRO
	 * @return
	 */
	@RequestMapping("driverList")
   public Object driverList(String lng, String lat, String cityName,Integer distance,Integer appraise,Integer singularNum
		   ,Integer pageNo,Integer pageSize,Integer carType){
	return orderItemsService.driverList(lng, lat, cityName, distance, appraise, singularNum,pageNo,pageSize,carType);
   }
	/**
	 * 确认订车-司机详情
	 * @param driverId
	 * @return
	 */
	@RequestMapping("driverDetail")
	 public Object driverDetail(Long driverId){
		return orderItemsService.driverDetail(driverId);
	   }
	
	/**
	 * 用户端   确认订车P022  
	 * @param driverId
	 * @return
	 */
	@RequestMapping("confirmTheOrdering")
	 public Object confirmTheOrdering(Long driverId,Long orderId,HttpServletRequest request){
		return orderItemsService.confirmTheOrdering(driverId,orderId,request);
	   }
	
	/**
	 * 是否接单
	 * @param orderId
	 * @param driverId
	 * @return
	 */
	@RequestMapping("isReceiptList")
	public Object isReceiptList(Long orderId,Long driverId,Integer language){
		return orderItemsService.isReceiptList(orderId,driverId,language);
	}
	/**
	 * 修改目的地、途经点  //修改之后需重新冻结预估价金额
	 * @param orderId
	 * @param way_to_place
	 * @param way_to_place_jingwei
	 * @param arrived_location
	 * @param arrived_position
	 * @param times //计算结束时间
	 * @return
	 */
	@RequestMapping("addWay")
	public Object addWay(@RequestBody String json){
		return orderItemsService.addWay( json);
	}
	/**
	 * 已完成-待评价P030 通过订单id 获取订单中司机的信息以及价格
	 * @param orderId
	 * @return
	 */
	@RequestMapping("getOrderDetail")
	public Object getOrderDetail(Long orderId){
		return orderItemsService.getOrderDetail(orderId);
	}
	/**
	 * 用户端用户主动取消  取消订单
	 * @param orderId
	 * @param language
	 * @param  aurora_alias  使用平台
	 * @return
	 */
	@RequestMapping("cancelOrder")
	public Object cancelOrder(Long orderId,Integer language,String customer_ip,HttpServletRequest request){
		return orderItemsService.cancelOrder(orderId, language,customer_ip,request);
	}
	//是否经过途经点
	@RequestMapping("viaPoint")
	public Object saveViaPoint(Long orderId,Integer type,Long uId){
		return orderItemsService.saveViaPoint(orderId,type,uId);
	}
	
	//取消是否收费判断
	@RequestMapping("usercancelOrderCount")
	public Object usercancelOrderCount(Long orderId){
		return orderItemsService.usercancelOrderCount(orderId);
	}
	//通过优惠劵id
	@RequestMapping("getCouponsIdQueryOrder")
	public  Object getCouponsIdQueryOrder(Long couponsId){
		return orderItemsService.getCouponsIdQueryOrder(couponsId);
	}
	//获取行程线路记录
	@RequestMapping("getOrderStroke")
	public  Object getOrderStroke(Long orderId){
		return orderItemsService.getOrderStroke(orderId);
	}
	//我的行程
	@RequestMapping("getMyItinerary")
	public  Object getMyItinerary(Long uId,Integer pageNo,Integer pageSize){
		return orderItemsService.getMyItinerary(uId,pageNo,pageSize);
	}
	 /**
	  * 删除我的行程中已完成 或者取消了的订单  逻辑删除
	  * @param uId
	  * @param pageNo
	  * @param pageSize
	  * @return
	  */
	@RequestMapping("getMyItineraryNotShowDel")
	public  Object getMyItineraryNotShowDel(Long orderId){
		return orderItemsService.getMyItineraryNotShowDel(orderId);
	}
	
	
    //司机订单状态变更
	@RequestMapping("changeOrderStatus")
	public  Object changeOrderStatus(Long orderId,Integer status,Integer driverId,Integer carType,Integer language,Long carId){
		return orderItemsService.changeOrderStatus(orderId,status,driverId,carType,language,carId);
	}
	//前端读取订单的经纬度
	@RequestMapping("readOrderFile")
	public  Object 	readTxtFile(Long orderId,Integer status,HttpServletRequest request){
		String result=orderItemsService.readTxtFile(orderId,status,request);
		return new ReturnData(result,200,"success");
   }
	
	
	//正常收费
	@RequestMapping("normalCharge")
	public  Object normalCharge(Long orderId,Integer carType,Integer language){
		return orderItemsService.normalCharge(orderId,carType,language);
	}
	
	/**
	 * 司机取消订单   东西太多，无法上车的理由将不收取乘客费用，但需要乘客确认
	 * @param orderId
	 * @param reason
	 * @param language
	 * @param isPay
	 * @return
	 */
	@RequestMapping("driverCancelOrder")
	public  Object driverCancelOrder(Long orderId,String reason,Integer language,Long driverId,String customer_ip){
		return orderItemsService.driverCancelOrder(orderId,reason,language,driverId,customer_ip);
	}
	/**
	 * 司机端  核实订单-改-P013 订单
	 * @param mileage
	 * @param times
	 * @param orderId
	 * @return
	 */
	@RequestMapping("getTheOrderPrice")
	 public Object getTheOrderPrice(@RequestBody String json){
		return orderItemsService.getTheOrderPrice(json);
	   }
	/**
	 * 司机 确认费用    直接扣卡中的金额
	 * @param mileage
	 * @param orderId
	 * @return
	 */
	@RequestMapping("confirmTheBill")
	 public Object confirmTheBill(@RequestBody String json,HttpServletRequest request){
		return orderItemsService.confirmTheBill(json,request);
	   }	
	/**8
	 * 司机端      取消订单-P018 取消订单明细
	 * @param orderId
	 * @return
	 */
	@RequestMapping("driverOrderDetail")
	 public Object driverOrderDetail(Long  orderId){
		return orderItemsService.driverOrderDetail(orderId);
	   }	
   	/**
   	 * 司机端  我的订单   司机的订单
   	 * @param orderId
   	 * @return
   	 */
	@RequestMapping("driverOrder")
	public Object driverOrder(Long  driverId,Integer pageNo,Integer pageSize){
		return orderItemsService.driverOrder(driverId,pageNo,pageSize);
	   }
	/**
	 * 司机端  已服务-P032 我的订单详情
	 * @param driverId
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("hasServicedriverOrderDetail")
	public Object hasServicedriverOrderDetail(Long  orderId){
		return orderItemsService.hasServicedriverOrderDetail(orderId);
	   }
	
	/**
	 * 查询订单详情
	 * @param orderId
	 * @return
	 */
	@RequestMapping("selectById")
	public  Object selectById(Long  orderId){
		return orderItemsService.selectById(orderId);
	}
	//司机不接单 直接取消订单 无需接收惩罚
	@RequestMapping("driverDidNotCancelOrder")
	public Object driverDidNotCancelOrder(Long orderId,Long driverId){
		return orderItemsService.driverDidNotCancelOrder(orderId,driverId);
	}
	
	
}
